from django.shortcuts import render

# Create your views here.
import json

from django.http import JsonResponse
from django.views import View

from users.models import User


class UploadAvatar(View):
    def post(self, request):
        """
        ①获取传入图片数据;
        ②存入FDFS;
        ③将图片地址存入user;
        ④返回完整地址
        :param request:
        :return:
        """
        # ①获取传入图片数据
        img_data = request.FILES.get('img')
        print(type(img_data), img_data)

        # ②存入FDFS
        # 导入扩展包中的 Fdfs_client 类
        from fdfs_client.client import Fdfs_client

        # 创建一个 Fdfs_client 类的实例对象
        # 注意: 添加的路径为 client.conf 配置文件的绝对路径:
        client = Fdfs_client(r'C:\Users\HQ\Desktop\\1\\the-tenth-power\TenSquare\TenSquare\utils\\fastdfs\client.conf')

        # 利用client对象上传文件;  注意：这里要通过read()方法将数据转换为二进制
        ret = client.upload_by_buffer(img_data.read())
        print(ret)

        # ret对象里可以获取文件名，再拼接上FastDFS 中 nginx 服务器的地址
        nginx_url = 'http://192.168.19.131:8888/'
        avatar_url = ret['Remote file_id']
        print(avatar_url)

        img_url = nginx_url + avatar_url

        # ③将图片地址存入user
        user = request.user
        current_user = User.objects.get(id=user.id)
        print(type(current_user), current_user)
        current_user.avatar = avatar_url
        current_user.save()
        print("执行数据库操作")
        print("数据库存入成功" + current_user.avatar.name)

        # ④返回完整地址
        return JsonResponse({
            "imgurl": img_url
        })